#include "pageLib.h"

PageLib::PageLib(){}

void PageLib::parsePage(const char *filename)
{
    XMLDocument xml; 
    if(xml.LoadFile(filename)) //LoadFile返回值为_errorID， _errorID初始为0，失败会修改_errorID的值
    {
        xml.PrintError();
        exit(-1);
    }
    
    XMLElement *category = xml.RootElement();//根
    XMLElement *channel = category->FirstChildElement("channel");
    XMLElement *title = channel->FirstChildElement("title");
    XMLElement *item = channel->FirstChildElement("item");

    while(item)
    {
        RssItem rss_item;

        regex reg("<[^>]*>"); //匹配< >

        XMLElement *item_title = item->FirstChildElement("title");//title结点
        rss_item.title = item_title->GetText(); //保存结点的内容

        XMLElement *item_link = item->FirstChildElement("link");//link
        rss_item.link= item_link->GetText();

        XMLElement *item_description = item->FirstChildElement("description");//description
        rss_item.description= item_description->GetText();
        rss_item.description = regex_replace(rss_item.description,reg,"");//去除多余标签

        _rss.push_back(rss_item); //保存到vector中
        item = item->NextSiblingElement();//item移动到下一个
    }
}

void PageLib::dumpPage(const string & filename)
{
    ofstream ofs(filename,ios::out|ios::app);
    
    //cout<<"起始偏移："<<begin<<endl;
    if(!ofs.good())
    {
        cerr<<"filename open failed!"<<endl;
        return;
    }

    for(int j=0; j<_rss.size();++j)
    {
        long begin = ofs.tellp();
        ofs << "<doc>" << endl
            << "\t" << "<id>" << i+1 << "</docid>" << endl
            << "\t" << "<url>"  << _rss[j].link  << "</url>"  << endl
            << "\t" << "<title>" << _rss[j].title << "</title>" << endl
            << "\t" << "<content>" << _rss[j].description << "</content>" << endl
            << "</doc>" << endl;
        ++i;
        long end = ofs.tellp();
        _offsetLib[i]=make_pair(begin,end-begin);
    }
    _rss.clear();
    ofs.close();
}

void PageLib::createOffset()
{

}

void PageLib::storeOffset(const string & filename)
{
    ofstream ofs(filename,ios::out|ios::app);
    if(!ofs.good())
    {
        cerr<<"storeOffset filename open failed!"<<endl;
        return;
    }

    for(int j = 1;j <= i;++j)
    {
        ofs << j <<"    "<<_offsetLib[j].first<<"   "<<_offsetLib[j].second<<endl;
    }
    ofs.close();
}